"""
负责Plc通信的模块
"""
import threading

from pymodbus.client.sync import ModbusTcpClient


class PlcCommunication(object):
    __lock = threading.Lock()
    __instance = None
    __init_flag = False

    def __new__(cls, *args, **kwargs):
        with PlcCommunication.__lock:
            if PlcCommunication.__instance is None:
                PlcCommunication.__instance = super().__new__(cls, *args, **kwargs)
        return PlcCommunication.__instance

    def __init__(self):
        if not self.__init_flag:
            self.__init_flag = True
            self.ip = "10.55.92.196"
            self.port = 502
            self.client = None
            self.online = False

    def reconnect_plc(self):
        """
        重新连接到Plc
        """
        self.client = ModbusTcpClient(self.ip, self.port)
        if self.client.connect():
            print("Plc连接成功")
            self.online = True
            return True
        else:
            self.client = None
            self.online = False
            return False

    def write_board_length(self, boardLength):
        """
        乘10,发整除
        """
        try:
            dataWrite = int(boardLength * 10)
            write_address = 690
            response = self.client.write_register(address=write_address, value=dataWrite)
            if not response.isError():
                return True
            else:
                return False
        except Exception as e:
            print(f"in write_board_length() error: {str(e)}")
            return False

    def check_connect(self):
        try:
            response = self.client.read_holding_registers(address=690, count=1)
            if not response.isError():
                # print(f"读取的值位: {response.registers[0]}")
                return True
            else:
                return False
        except Exception as e:
            print(f"in check_connect() error: {str(e)}")
            return False


if __name__ == '__main__':
    plcHandler = PlcCommunication()
    res = plcHandler.reconnect_plc()
    if res:
        res = plcHandler.write_board_length(105.6)
        if res:
            print("写入成功")
        else:
            print("写入失败")
    else:
        print("连接失败")

    res = plcHandler.check_connect()
    if res:
        print("Plc在线")
    else:
        print("Plc不在线")
